#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <assert.h>
#include <fcntl.h>       
#include <unistd.h>


#define BUFFER_SIZE 1024

const char* ip = "0.0.0.0";
char* port = "9876";

int main(int argc, char const *argv[])
{	
	char buf[BUFFER_SIZE];  
	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(ip);
	serv_addr.sin_port = htons(atoi(port));

	int serv_sock = socket(PF_INET, SOCK_STREAM, 0);
	assert(serv_sock>=0);
	
	int ret = bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
	assert(ret>=0);

	ret = listen(serv_sock, 5);
	assert(ret>=0);
	
	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_size = sizeof(clnt_addr);  // 这里必须先声明大小吗？
	int i;
	for(i=0; i<2; i++){ //两个连接
		int connfd = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
		assert(connfd>0);
		printf("Connected client %d \n", i+1);

		int str_len;
		while((str_len=read(connfd, buf, BUFFER_SIZE))!=0){
			printf("client send:");
			fputs(buf, stdout);	
			write(connfd, buf, str_len);		
		}	
		close(connfd);
		printf("connection closed\n");
	}
	close(serv_sock);
	return 0;
}